package com.module.product.manager;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.db.HibernateSessionFactory;
import base.manager.GenericHibernateManager;
import base.util.Page;
import base.util.StringUtil;

import com.module.product.common.ProductConstant;
import com.module.product.dao.AttrGroupDao;
import com.module.product.dao.AttrItemComboxDao;
import com.module.product.dao.AttrItemDao;
import com.module.product.dao.AttrValueDao;
import com.module.product.vo.AttrItem;
import com.module.product.vo.AttrItemCombox;


/**
*
* 商品属性项业务处理类
*
* @author  王勇云
* @version  [V1.0, Jul 22, 2011]
* @see  [相关类/方法]
* @since  [二代服务平台/商品属性项]
*/
public class AttrItemManager extends GenericHibernateManager<AttrItem, String>{
    private static final AttrItemManager instance = new AttrItemManager();
    
    static Logger logger = Logger.getLogger(AttrItemManager.class.getName());
    private AttrItemManager(){}
    
    public synchronized static AttrItemManager getInstance() {
        return instance;
    }
    AttrItemDao dao = AttrItemDao.getInstance();
    AttrGroupDao attrGroupDao = AttrGroupDao.getInstance();
    AttrValueDao attrValueDao = AttrValueDao.getInstance();
    AttrItemComboxDao comboxDao = AttrItemComboxDao.getInstance();
    
    public boolean add(AttrItem obj) throws Exception
    {
    	Session session =HibernateSessionFactory.getSession();
    	Transaction tx =session.beginTransaction();
    	boolean flag = false;
    	try{
    		 if(StringUtils.isBlank(obj.getId())){//添加
    	            obj.setStatus(CUDEnum.C.toString());
    	            obj.setCreateTime(new Date());
    	            attrGroupDao.updateAttrNumbyId(session,obj.getAttrGroup(),1);
    	        }else{
    	            obj.setStatus(CUDEnum.U.toString());
    	            obj.setUpdateTime(new Date());
    	            comboxDao.delComboxByAttrId(session, obj.getId());//清空之前数据
    	        }
    		 	flag =  dao.saveOrUpdate(session,obj);
    		 	if(!StringUtil.isNull(obj.getComboxValue())){
    		 		this.saveCombox(session, obj);
    		 	}
    		 	tx.commit();
	    	}catch(Exception e){
	    		tx.rollback();
	    		throw e;
	    	}finally{
	    		this.closeSession();
	    	}
       
        return flag;
    }
    /**
     * 保存下拉类型的选择值
     * @param session
     * @param obj
     * @author dengsq
     * @return true or false
     */
    private  boolean saveCombox(Session session,AttrItem obj) throws Exception{
    	String[] comboxItem = obj.getComboxValue().split(ProductConstant.SPLIT_VAULE);
    	boolean flag = false;
 		int index = comboxItem.length;
 		for(int i=0;i<index;i++){
 			AttrItemCombox combox = new AttrItemCombox();
 			combox.setDisplayvalue(comboxItem[i]);
 			combox.setHiddenvalue(comboxItem[i]);
 			combox.setAttrId(obj.getId());
 			flag = comboxDao.save(session, combox);
 		}
 		return flag;
    }
    
    /**
     * 删除属性
     * @throws Exception 
     */
    public boolean delete(AttrItem obj) throws Exception
    {
        Session session =HibernateSessionFactory.getSession();
        Transaction tx =session.beginTransaction();
        int i = obj.getId().split(",").length;
        boolean flag = false;
        try{
        	  attrGroupDao.updateAttrNumbyId(session,dao.get(session,obj.getId().split(",")[0].replaceAll("'","")).getAttrGroup(),-i);
        	  flag = dao.deleteObjs(session,obj);
        	  tx.commit();
        }catch(Exception e){
    	 if (tx != null) {
           tx.rollback();
           }
    	 throw e;
    	}finally{
    		this.closeSession();
    	}
      
        return flag;
    }
    public boolean update(AttrItem obj) throws Exception
    {
    	Session session = HibernateSessionFactory.getSession();
    	boolean flag = false;
    	try{
    		flag =  dao.update(session,obj);
    	}catch(Exception e){
    		throw e;
    		
    	}finally{
    		this.closeSession();
    	}
    	return flag;
    }
    
//    public AttrItem get(String id)
//    {
//        return get(id);
//    }
    
    public Page getList(AttrItem obj,Page page) throws Exception{
    	Session session =HibernateSessionFactory.getSession();
    	try{
    	    	page = dao.getList(session,obj,page);
	    	}catch(Exception e){
	    		throw e;
	    		
	    	}finally{
	    		this.closeSession();
	    	}
        return page;
    }
    
    public List<AttrItem> listByGroupId(AttrItem obj) throws Exception{
    	Session session =HibernateSessionFactory.getSession();
    	Connection conn = session.connection();
    	Transaction tx =session.beginTransaction();
    	List<AttrItem> list  = new ArrayList();
    	try{
    	    	list = dao.listByGroupId(conn,obj.getAttrGroup(),obj.getProductId());;
	    	}catch(Exception e){
	    		throw e;
	    	
	    	}finally{
	    		this.close(conn);
	    		this.closeSession();
	    	}
        return list;
    }
    
    /**
     * 根据属性ID查询对应的下拉值
     * @param attrId
     * @return
     * @throws Exception
     * @author Dengsq
     */
    public List<String> getComboxValueByAttrId(String attrId)throws Exception{
    	try {
			return comboxDao.getComboxByAtrrId(this.getSession(), attrId);
		} catch (Exception e) {
			throw e;
		}finally{
			this.closeSession();
		}
    }
    
    public AttrItem getAttrItem(String id) throws Exception{
    	AttrItem item = this.get(id);
    	if(this.isCombox(item)){
    		item.setComboxValue(this.getComboxVlaue(item.getId()));
    	}
    	return item;
    }
    
    private String getComboxVlaue(String attrId ) throws Exception{
    	List<String> list = this.getComboxValueByAttrId(attrId);
    	StringBuffer vlaue = new StringBuffer();
    	if(list != null && !list.isEmpty()){
    		for(String name:list){
    			if(vlaue.length()==0)
    				vlaue.append(name);
    			else
    				vlaue.append(";").append(name);
    		}
    	}
    	return vlaue.toString();
    }	
    
	private boolean isCombox(AttrItem item){
		if(item != null && item.getType() != null
				&&(item.getType().equals(ProductConstant.ATTR_TYPE_CHECKBOX) 
		    			|| item.getType().equals(ProductConstant.ATTR_TYPE_SELECT)))
			return true;
		return false;
	}
	
	
	@Override
	public GenericHibernateDao<AttrItem, String> getDao() {
		return dao;
	}

}
